package com.sheeran.aichat.dto.common.rest;

import com.fasterxml.jackson.annotation.JsonPropertyOrder;
import com.sheeran.aichat.exception.BusinessException;
import com.sheeran.aichat.utils.rest.ResponseCode;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.apache.poi.ss.formula.functions.T;
import org.springframework.util.StringUtils;

import java.io.Serializable;

/**
 * @author: sheeran
 * @create: 2025/02/11
 */
@Data
@NoArgsConstructor
@AllArgsConstructor
@JsonPropertyOrder({ "resultCode", "resultMsg", "data" })
public class ChatWrappedResponse<T> implements Serializable {
    private static final long serialVersionUID = 6743074179921180551L;

    /**
     * 返回码
     */
    private int resultCode;

    /**
     * 返回描述
     */
    private String resultMsg;

    /**
     * 返回数据
     */
    private T data;

    public ChatWrappedResponse(ResponseCode responseCode, T result) {
        this.resultCode = responseCode.getCode();
        this.resultMsg = responseCode.getMsg();
        this.data = result;

        if (result != null && BaseOperateResponse.class.isAssignableFrom(result.getClass())) {
            // 前端需要将Reason放入到resultMsg中
            String reason = ((BaseOperateResponse) result).getReason();
            if (StringUtils.hasText(reason)) {
                this.resultMsg = reason;
            }
        }
    }

    public void checkSuccess() {
        if (this.resultCode != 0) {
            throw new BusinessException(ResponseCode.COMMON_ERROR, this.resultMsg);
        }
    }
}
